/**
 * Created by maiseries on 2017/9/25.
 */
import React from 'react';
import {
    Platform,
    DeviceEventEmitter
} from 'react-native'
import Axios from 'axios';
import Qs from 'qs';

import Constants from '../config/Constants'

Axios.defaults.baseURL = Constants.DEV_MODE ? Constants.DEV_BASE_URL : Constants.BASE_URL;
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Axios.defaults.timeout = Constants.REQUEST_TIMEOUT;

export default class Request extends React.Component {

    /**
     * post request
     * @param options = {url,params}
     * @returns {Promise.<*>} = response
     */
    static async post(options) {
        options.params = options.params ? options.params : {};
        options.params.clientType = Platform.OS === 'ios' ? '02' : '01';
        console.log('Parameter --->');
        console.log(options);
        return Axios.post(options.url, Qs.stringify(options.params)).then(res => this.NetFilter(res)).then(res => this.WorkFilter(res)).catch(err => this.NetError(err))
    }

    static async upload(options) {
        console.log('Parameter --->');
        console.log(options);
        let params = new FormData();
        if(!options.params.uri){
            return {
                message: '所选文件不存在',
                code: 'Y60414'
            }
        }
        params.append('file', {
            uri: options.params.uri,
            type: 'multipart/form-data',
            name: 'image.png'
        });
        params.append('clientType', Platform.OS === 'ios' ? '02' : '01');
        params.append('accessToken', user.token);
        return Axios.post(options.url, params, {
            headers: {'Content-Type': 'multipart/form-data'},
        }).then(res => this.NetFilter(res)).then(res => this.WorkFilter(res)).catch(err => this.NetError(err))
    }

    static async sleep(times) {
        return new Promise(res => {
            setTimeout(res, times)
        })
    }

    static valid(res) {
        if (res.code === 'S10000') {
            return res.data;
        } else {
            throw res;
        }
    }

    /**
     * post request with token
     * @param options
     * @returns {Promise.<*>}
     */
    static async token(options) {
        options.params = options.params ? options.params : {};
        options.params.accessToken = user.token;
        return await this.post(options);
    }


    static NetFilter(res) {
        //统一业务请求错误处理
        console.log('Request --->');
        console.log(res);
        console.log('------------');
        return res.data
    }

    static WorkFilter(res) {
        if ('Y69999' === res.code) {
            storage.remove({key: Constants.ACCESS_TOKEN_STORAGE});
            DeviceEventEmitter.emit(Constants.LISTENER_LOGGING);
        }
        return res
    }

    static NetError(err) {
        //统一网络连接错误处理
        console.log('Request Error --->');
        console.log(err);
        console.log('------------------');
        //Network Error
        if (err.message.indexOf('Network Error') === -1) {
            return {
                message: '网络连接错误',
                code: 'Y60999'
            };
        }
        //Request failed with status code 404
        if (err.message.indexOf('code 404') === -1) {
            return {
                message: '网络连接未找到',
                code: 'Y60404'
            };
        }
        //Request failed with status code 500
        if (err.message.indexOf('code 500') === -1) {
            return {
                message: '网络请求异常',
                code: 'Y60500'
            };
        }
        //timeout of 30000ms exceeded
        if (err.message.indexOf('timeout') !== -1) {
            return {
                message: '网络请求超时',
                code: 'Y60998'
            }
        }
        return err
    }

}